﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using PHMEE.Admin.Application.Contracts;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;
using Volo.Abp.Uow;

namespace PHMEE.Admin
{
    public class CollectParaAppService : PHMEEAdminAppService, ICollectParaAppService
    {

        private IGuidGenerator _guidGenerator;
        private readonly IRepository<SysPara, Guid> _sysparaRepository;
        private readonly IVibChannelParaRepository _vibChannelPara;
        private readonly IRepository<VibPara, Guid> _vibPara;
        private readonly IRepository<Threshold, Guid> _thresholdRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private ILogger<CollectParaAppService> _logger;
        public CollectParaAppService(IGuidGenerator guidGenerator, IVibChannelParaRepository vibChannelPara, IRepository<VibPara, Guid> vibPara, IUnitOfWorkManager unitOfWorkManager, IRepository<SysPara, Guid> sysparaRepository, IRepository<Threshold, Guid> thresholdRepository, ILogger<CollectParaAppService> logger)
        {
            _guidGenerator = guidGenerator;
            _vibChannelPara = vibChannelPara;
            _vibPara = vibPara;
            _unitOfWorkManager = unitOfWorkManager;
            _sysparaRepository = sysparaRepository;
            _thresholdRepository = thresholdRepository;
            _logger = logger;
        }

        /// <summary>
        /// 创建数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateCollectParameterAsync(List<VibChannelParaCreateDto> VibChannelList)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                foreach (var VibChannel in VibChannelList)
                {
                    var vibParaDto = VibChannel.VibParaList;
                    vibParaDto[0].Id = _guidGenerator.Create();
                    vibParaDto[0].HighFreq = (int)(vibParaDto[0].HighFreq);
                    var vibChannelPara = ObjectMapper.Map<VibChannelParaCreateDto, VibChannelPara>(VibChannel);
                    await _vibChannelPara.InsertAsync(vibChannelPara);
                }
                await _unitOfWorkManager.Current.SaveChangesAsync();
            }
        }
        /// <summary>
        /// 查询VibChannelPara集合根据SysParaId--Form表单查看修改用
        /// </summary>
        /// <param name="SysParaId"></param>
        /// <returns></returns>
        public async Task<List<VibChannelParaFormDto>> GetBySysCollectParaAsync(Guid SysParaId)
        {
            var vibChannelParas = await _vibChannelPara.GetAllByVibChannelWithMqttAsync(SysParaId);
            return ObjectMapper.Map<List<VibChannelPara>, List<VibChannelParaFormDto>>(vibChannelParas);
        }
        /// <summary>
        /// 查询单个通道对应的测点
        /// </summary>
        /// <param name="SysParaId"></param>
        /// <param name="chno"></param>
        /// <returns></returns>
        public async Task<ReturnParaDto> GetByPoint(string collectorCode, int chno)
        {
            var queryable = await _sysparaRepository.GetQueryableAsync();
            queryable = queryable.Where(item => item.CollectorCode == collectorCode);
            var sysPara = queryable.FirstOrDefault();
            if (sysPara == null || sysPara.Id == Guid.Empty)
            {
                throw new UserFriendlyException("采集站编码不存在，请检查输入");
            }

            var pointId_pipeId = await _vibChannelPara.GetByCollectPoint(sysPara.Id, chno);
            //(Guid pointId, Guid pipeId, float HighFreq)
            var returnParaDto = new ReturnParaDto
            {
                pointId = pointId_pipeId.PointId,
                pipeId = pointId_pipeId.Id,
                HighFreq = sysPara.SamplingFrequency
            };
            return returnParaDto;
        }
        /// <summary>
        ///  获取VibChannelPara集合--Mqtt下发时使用
        /// </summary>
        /// <param name="collectorCode">采集器编码</param>
        /// <returns></returns>
        public async Task<List<VibChannelParaDto>> GetByVibChannelListMqttAsync(string collectorCode)
        {
            var sysPara = await _sysparaRepository.FirstOrDefaultAsync(x => x.CollectorCode == collectorCode);
            if (sysPara == null)
                throw new UserFriendlyException("没有对应的SysPara数据");
            //查询最终数据结构
            var vibChannelParas = await _vibChannelPara.GetByVibChannelWithMqttAsync(sysPara.Id);
            var dtolist = ObjectMapper.Map<List<VibChannelPara>, List<VibChannelParaDto>>(vibChannelParas);

            foreach (var dto in dtolist)
            {
                //var a = dto.VibParaList.Count;
                foreach (var vibPara in dto.VibParaList)
                {
                    vibPara.HighFreq = (int)(vibPara.HighFreq / 2.56f);
                }
                var vibChannel = vibChannelParas.FirstOrDefault(v => v.ChNo == dto.ChNo);
                if (vibChannel?.PointId.HasValue ?? false)
                {
                    Guid pointId = vibChannel.PointId.Value;
                    var thresholds = await _thresholdRepository.GetListAsync(t => t.PointId == pointId && t.isEnable);

                    foreach (var threshold in thresholds)
                    {
                        if (threshold.ThirdThreshold.HasValue && threshold.ThirdThreshold.Value != 0)
                        {
                            dto.LimitParaList.Add(new LimitParaDto
                            {
                                Level = 3,
                                Limit = threshold.ThirdThreshold.Value,
                                Dir = SernorStyleEnum.D,
                                Code = threshold.LimitPara
                            });
                        }

                        if (threshold.FourthThreshold.HasValue && threshold.FourthThreshold.Value != 0)
                        {
                            dto.LimitParaList.Add(new LimitParaDto
                            {
                                Level = 4,
                                Limit = threshold.FourthThreshold.Value,
                                Dir = SernorStyleEnum.D,
                                Code = threshold.LimitPara
                            });
                        }
                        // 后续启用一级二级阈值的时候继续添加其他级别的阈值条件
                    }
                }
            }
            return dtolist;
        }
        /// <summary>
        /// 更新策略数据
        /// </summary>
        /// <param name="intput"></param>
        /// <returns></returns>
        public async Task UpdateCollectorAsync(List<VibChannelParaUpdateDto> VibChannelListDto, Guid sysParaId)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                var vibChannelParas = await _vibChannelPara.GetListAsync(x => x.SysParaID == sysParaId);
                if (vibChannelParas.Count != 0)
                {
                    foreach (var VibChannelDto in VibChannelListDto)
                    {
                        var vibChannelPara = vibChannelParas.FirstOrDefault(v => v.ChNo == VibChannelDto.ChNo);
                        var vibPare = await _vibPara.FirstOrDefaultAsync(v => v.VibChannelId == vibChannelPara.Id);
                        vibPare.HighFreq = (int)(vibPare.HighFreq);
                        vibChannelPara.VibParaList[0] = vibPare;
                        if (vibChannelPara != null)
                        {
                            ObjectMapper.Map(VibChannelDto, vibChannelPara);
                            await _vibChannelPara.UpdateAsync(vibChannelPara);
                        }
                    }
                    await _unitOfWorkManager.Current.SaveChangesAsync();
                }
                else
                {
                    throw new UserFriendlyException("没有相关sysParaId的数据");
                }
            }
        }
    }
}
